
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class Main {
	public static final double DELTA = Math.nextUp(0);
	private static int n;
	private static int[] C, CC;

	private static double F(double x) {
		double res = 0;
		double cur = 1;
		for (int i = 0; i <= n; i++) {
			res += cur * C[i];
			cur *= x;
		}
		return res;
	}

	private static double FF(double x) {
		double res = 0;
		double cur = 1;
		for (int i = 0; i < n; i++) {
			res += cur * CC[i];
			cur *= x;
		}
		return res;
	}

	public static void main(String[] args) {
		Scanner S = new Scanner(System.in);
		System.out.print("请输入方程次数: ");
		n = S.nextInt();
		C = new int[n + 1];
		CC = new int[n];
		System.out.print("请输入方程参数(" + n + "-0): ");
		for (int i = n; i >= 0; i--) {
			C[i] = S.nextInt();
			if (i != 0) CC[i - 1] = C[i] * i;
		}
		System.out.print("方程: ");
		boolean AllZero = true, XAllZero = true;
		for (int i = n; i >= 0; i--) {
			if (C[i] == 0) continue;
			AllZero = false;
			if (i != 0) XAllZero = false;
			if (i != n) System.out.print(C[i] < 0 ? '-' : '+');
			if (!(C[i] == 1 && i != 0)) System.out.print(Math.abs(C[i]));
			if (i > 0) {
				System.out.print('n');
				if (i != 1)
					System.out.print("^" + i);
			}
		}
		if (AllZero) {
			System.out.print("0=0");
			System.out.println("解: X属于任意实数");
			return;
		}
		System.out.println("=0");
		if (XAllZero) {
			System.out.println("解: 无解");
			return;
		}
		System.out.print("请输入一个X的基准值: ");
		double x = S.nextDouble();
		S.close();
		System.out.println("求解中..");
		long count = 0;
		long st = System.nanoTime();
		double tmp;
		while (true) {
			tmp = F(x);
			if (Math.abs(tmp) <= DELTA) break;
			x -= tmp / FF(x);
			count++;
		}
		st = System.nanoTime() - st;
		System.out.println("X = " + x);
		System.out.println("时间: " + TimeUnit.NANOSECONDS.toMillis(st) + "\n迭代次数: " + count);
	}
}
